<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello WebSocket</title>
<!--    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">-->
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://fastly.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js"></script>
    <script src="https://fastly.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>

<!--    <script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>-->
<!--    <script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>-->

</head>
<body>
<noscript><h2 style="color: #ff0000">浏览器不支持Javascript！Websocket依赖于启用的Javascript,请启用Javascript并重新加载此页面！</h2></noscript>
<div id="main-content" class="container">
    <div class="row">
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="connect">WebSocket 连接:</label>
                    <button id="connect" class="btn btn-default" type="submit">连接</button>
                    <button id="disconnect" class="btn btn-default" type="submit" disabled="disabled">断开
                    </button>
                </div>
            </form>
        </div>
        <div class="col-md-6">
            <form class="form-inline">
                <div class="form-group">
                    <label for="name">你叫什么?</label>
                    <input type="text" id="name" class="form-control" placeholder="输入你的名字">
                </div>
                <button id="send" style="overflow: auto" class="btn btn-default" type="submit">发送</button>
            </form>
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <table id="conversation" class="table table-striped">
                <thead>
                <tr>
                    <th>消息</th>
                </tr>
                </thead>
                <tbody id="greeting">
                </tbody>
            </table>
        </div>
    </div>
</div>
</body>
<script src="https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.js"></script>
<script>
    // const url = "ws://localhost:9900/api/monitor/ws";
    const url = "ws://192.168.209.3:9900/api/monitor/ws";
    // var socket = new SockJS('http://localhost:9900/ws');

    const stompClient = new StompJs.Client({
        brokerURL: url,
        connectHeaders: {


            // login: 'user',
            // passcode: 'password',
        },
        debug: function (str) {


            console.log(str);
        },
        //重连间隔 ms
        reconnectDelay: 5000,
        //发送心跳 ms
        heartbeatIncoming: 4000,
        //接收心跳 ms
        heartbeatOutgoing: 4000,
        logRawCommunication: false,
    });

    //默认使用WebSockets，如果浏览器不支持，则回退到SockJS
    // if (typeof WebSocket !== 'function') {


        // 对于SockJS，需要设置一个工厂来创建一个新的SockJS实例
        // 用于每次（重新）连接
        stompClient.webSocketFactory = function () {


            // 请注意，URL与WebSocket URL不同
            // return new SockJS('http://fssocket.nbiot.muguasoft.com:7602/api/monitor/ws');
            return new SockJS('http://192.168.209.23:9900/api/monitor/ws');
        };
    // }

    stompClient.onConnect = (frame) => {


        setConnected(true);
        console.log('Connected: ' + frame);
        //在这里将订阅改成 /topic/+机场的网关，即可收到点对点发送的消息
        stompClient.subscribe('/topic/8UUXN2800A00HX', (greeting) => {


            console.log(JSON.parse(greeting.body));
        });
    };
    stompClient.onWebSocketError = (error) => {
        console.error('Error with websocket', error);
    };

    stompClient.onStompError = (frame) => {
        console.error('Broker reported error: ' + frame.headers['message']);
        console.error('Additional details: ' + frame.body);
    };

    function setConnected(connected) {


        $("#connect").prop("disabled", connected);
        $("#disconnect").prop("disabled", !connected);
        if (connected) {


            $("#conversation").show();
        }
        else {


            $("#conversation").hide();
        }
        $("#greetings").html("");
    }

    function connect() {


        stompClient.activate();
    }

    function disconnect() {


        stompClient.deactivate();
        setConnected(false);
        console.log("Disconnected");
    }

    function sendName() {


        stompClient.publish({


            destination: "/app/droneControl",
            body: JSON.stringify({
                "latitude":"30.24961242103",
                "longitude":"119.90185824462",
                "method":"flyToPointUpdate",
                "gateway":"8UUXN2800A00HX",
            })
        });
    }
    // body: JSON.stringify({
    //     "method":"control",
    //     "gateway":"8UUXN2800A00HX",
    //     "x":17,
    //     "y":0,
    //     "h":0,
    //     "w":0
    // })
    function showGreeting(message) {


        $("#greetings").append("<tr><td>" + message + "</td></tr>");
    }

    $(function () {


        $("form").on('submit', (e) => e.preventDefault());
        $( "#connect" ).click(() => connect());
        $( "#disconnect" ).click(() => disconnect());
        $( "#send" ).click(() => sendName());
    });
</script>
</html>
